package com.example.infrastructure.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * Jackson JSON工具类
 * 
 * @author wangal
 * @since 2025-01-26
 */
@Slf4j
public class JsonUtils {
    
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    
    static {
        // 配置ObjectMapper
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
        OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        OBJECT_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        
        // 注册Java8时间模块
        OBJECT_MAPPER.registerModule(new JavaTimeModule());
        
        // 设置日期格式
        OBJECT_MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }
    
    /**
     * 获取ObjectMapper实例
     */
    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }
    
    /**
     * 对象转JSON字符串
     */
    public static String toJson(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转JSON失败: {}", e.getMessage(), e);
            throw new RuntimeException("对象转JSON失败", e);
        }
    }
    
    /**
     * 对象转JSON字符串（美化格式）
     */
    public static String toPrettyJson(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转美化JSON失败: {}", e.getMessage(), e);
            throw new RuntimeException("对象转美化JSON失败", e);
        }
    }
    
    /**
     * JSON字符串转对象
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        if (!StringUtils.hasText(json) || clazz == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            log.error("JSON转对象失败: {}", e.getMessage(), e);
            throw new RuntimeException("JSON转对象失败", e);
        }
    }
    
    /**
     * JSON字符串转对象（使用TypeReference）
     */
    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        if (!StringUtils.hasText(json) || typeReference == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, typeReference);
        } catch (IOException e) {
            log.error("JSON转对象失败: {}", e.getMessage(), e);
            throw new RuntimeException("JSON转对象失败", e);
        }
    }
    
    /**
     * JSON字符串转List
     */
    public static <T> List<T> fromJsonToList(String json, Class<T> clazz) {
        if (!StringUtils.hasText(json) || clazz == null) {
            return null;
        }
        try {
            JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, clazz);
            return OBJECT_MAPPER.readValue(json, javaType);
        } catch (IOException e) {
            log.error("JSON转List失败: {}", e.getMessage(), e);
            throw new RuntimeException("JSON转List失败", e);
        }
    }
    
    /**
     * JSON字符串转Map
     */
    public static Map<String, Object> fromJsonToMap(String json) {
        if (!StringUtils.hasText(json)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, new TypeReference<Map<String, Object>>() {});
        } catch (IOException e) {
            log.error("JSON转Map失败: {}", e.getMessage(), e);
            throw new RuntimeException("JSON转Map失败", e);
        }
    }
    
    /**
     * JSON字符串转指定类型的Map
     */
    public static <K, V> Map<K, V> fromJsonToMap(String json, Class<K> keyClass, Class<V> valueClass) {
        if (!StringUtils.hasText(json) || keyClass == null || valueClass == null) {
            return null;
        }
        try {
            JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructMapType(Map.class, keyClass, valueClass);
            return OBJECT_MAPPER.readValue(json, javaType);
        } catch (IOException e) {
            log.error("JSON转Map失败: {}", e.getMessage(), e);
            throw new RuntimeException("JSON转Map失败", e);
        }
    }
    
    /**
     * 对象转Map
     */
    public static Map<String, Object> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        return OBJECT_MAPPER.convertValue(obj, new TypeReference<Map<String, Object>>() {});
    }
    
    /**
     * Map转对象
     */
    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
        if (map == null || clazz == null) {
            return null;
        }
        return OBJECT_MAPPER.convertValue(map, clazz);
    }
    
    /**
     * 对象深拷贝
     */
    public static <T> T deepCopy(T obj, Class<T> clazz) {
        if (obj == null || clazz == null) {
            return null;
        }
        try {
            String json = toJson(obj);
            return fromJson(json, clazz);
        } catch (Exception e) {
            log.error("对象深拷贝失败: {}", e.getMessage(), e);
            throw new RuntimeException("对象深拷贝失败", e);
        }
    }
    
    /**
     * 判断字符串是否为有效JSON
     */
    public static boolean isValidJson(String json) {
        if (!StringUtils.hasText(json)) {
            return false;
        }
        try {
            OBJECT_MAPPER.readTree(json);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
    
    /**
     * 安全的JSON转换（不抛异常）
     */
    public static <T> T fromJsonSafe(String json, Class<T> clazz) {
        try {
            return fromJson(json, clazz);
        } catch (Exception e) {
            log.warn("JSON转换失败，返回null: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 安全的对象转JSON（不抛异常）
     */
    public static String toJsonSafe(Object obj) {
        try {
            return toJson(obj);
        } catch (Exception e) {
            log.warn("对象转JSON失败，返回null: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 获取JSON字符串中指定字段的值
     */
    public static Object getValueFromJson(String json, String fieldName) {
        if (!StringUtils.hasText(json) || !StringUtils.hasText(fieldName)) {
            return null;
        }
        try {
            Map<String, Object> map = fromJsonToMap(json);
            return map != null ? map.get(fieldName) : null;
        } catch (Exception e) {
            log.warn("从JSON中获取字段值失败: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 合并两个JSON对象
     */
    public static String mergeJson(String json1, String json2) {
        if (!StringUtils.hasText(json1)) {
            return json2;
        }
        if (!StringUtils.hasText(json2)) {
            return json1;
        }
        try {
            Map<String, Object> map1 = fromJsonToMap(json1);
            Map<String, Object> map2 = fromJsonToMap(json2);
            if (map1 != null && map2 != null) {
                map1.putAll(map2);
                return toJson(map1);
            }
            return json1;
        } catch (Exception e) {
            log.error("合并JSON失败: {}", e.getMessage(), e);
            return json1;
        }
    }
    
    /**
     * 格式化JSON字符串
     */
    public static String formatJson(String json) {
        if (!StringUtils.hasText(json)) {
            return json;
        }
        try {
            Object obj = OBJECT_MAPPER.readValue(json, Object.class);
            return toPrettyJson(obj);
        } catch (Exception e) {
            log.warn("格式化JSON失败: {}", e.getMessage());
            return json;
        }
    }
    
    /**
     * 压缩JSON字符串（移除空格和换行）
     */
    public static String compactJson(String json) {
        if (!StringUtils.hasText(json)) {
            return json;
        }
        try {
            Object obj = OBJECT_MAPPER.readValue(json, Object.class);
            return toJson(obj);
        } catch (Exception e) {
            log.warn("压缩JSON失败: {}", e.getMessage());
            return json;
        }
    }
}